package com.example.andoridclient;

import global.Global;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;



import android.text.TextUtils;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.TextView;

public class RegisterActivity extends Activity implements
		OnClickListener, OnFocusChangeListener {
	
	private static final int SUCCESS = 1;
	private static final int LOADING = -1;
	private static final int UNLOADING = -2;
	
	EditText username;
	EditText password;
	EditText ensurepassword;
	EditText code;
	RadioButton radioman;
	RadioButton radiowoman;
	EditText phone;
	EditText realname;
	EditText idcard;
	List<NameValuePair> registerparamsList;

	TextView usernameWarn;
	TextView passwordWarn;
	TextView ensurepasswordWarn;
	TextView codeWarn;
	TextView phoneWarn;
	TextView realnameWarn;
	TextView idcardWarn;

	ProgressBar progressBar;
	
	Button register;
	
	ProgressDialog progressDialog;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_register);

		username = (EditText) findViewById(R.id.EditTextUserNameRegister);
		password = (EditText) findViewById(R.id.editTextPasswordRegister);
		ensurepassword = (EditText) findViewById(R.id.EditTextEnsurePassword);
		radioman = (RadioButton) findViewById(R.id.radioMan);
		radiowoman = (RadioButton) findViewById(R.id.radioWoman);
		code = (EditText) findViewById(R.id.editTextcode);
		phone = (EditText) findViewById(R.id.editTextPhoneRegister);
		realname = (EditText) findViewById(R.id.EditTextRealnameRegister);
		idcard = (EditText) findViewById(R.id.editText3IDcardRegister);
		usernameWarn = (TextView) findViewById(R.id.textViewUserNameWarn);
		passwordWarn = (TextView) findViewById(R.id.TextViewPasswordWarn);
		ensurepasswordWarn = (TextView) findViewById(R.id.TextViewEnsureWarn);
		codeWarn = (TextView) findViewById(R.id.textViewCodeWarn);
		phoneWarn = (TextView) findViewById(R.id.TextViewPhoneWarn);
		realnameWarn = (TextView) findViewById(R.id.TextViewRealnameWarn);
		idcardWarn = (TextView) findViewById(R.id.TextViewIDCardWarn);
		register = (Button)findViewById(R.id.buttonRegister);
		
		register.setOnClickListener(this);
		username.setOnFocusChangeListener(this);
		password.setOnFocusChangeListener(this);
		ensurepassword.setOnFocusChangeListener(this);
		code.setOnFocusChangeListener(this);
		phone.setOnFocusChangeListener(this);
		realname.setOnFocusChangeListener(this);
		idcard.setOnFocusChangeListener(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.register, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	// 点击事件
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.buttonRegister:
			if (!Check()) {
				return;
			}
			registerparamsList = new ArrayList<NameValuePair>();
			registerparamsList.add(new BasicNameValuePair("Code", code
					.getText().toString()));
			registerparamsList.add(new BasicNameValuePair("Username", username
					.getText().toString()));
			registerparamsList.add(new BasicNameValuePair("Password", password
					.getText().toString()));
			registerparamsList.add(new BasicNameValuePair("Sex", radioman
					.isChecked() ? "男" : "女"));
			registerparamsList.add(new BasicNameValuePair("PhoneNumber", phone
					.getText().toString()));
			registerparamsList.add(new BasicNameValuePair("Realname", realname
					.getText().toString()));
			registerparamsList.add(new BasicNameValuePair("IDCardNum", idcard
					.getText().toString()));

			new Thread(runnable).start();
			break;
		default:
			break;
		}
	}

	// 线程
	Runnable runnable = new Runnable() {
		@Override
		public void run() {
			handler.sendEmptyMessage(LOADING);
			String result = Global.POST("Register/Register", registerparamsList);
			try {
				JSONObject r = new JSONObject(result);
				if (TextUtils.isEmpty(r.get("error").toString())) {
					handler.sendEmptyMessage(SUCCESS);
				}
				else {
					Message message =new Message();
					message.obj = r.get("error");
					handler.sendMessage(message);
				}
			} catch (JSONException e) {
				// TODO: handle exception
				Message message = new Message();
				message.obj = result;
				handler.sendMessage(message);
			}
			finally
			{
				handler.sendEmptyMessage(UNLOADING);
			}
		}
	};
	// UI Handler
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			// 成功
			case SUCCESS:
				new AlertDialog.Builder(RegisterActivity.this).setTitle("提示")
						.setMessage("注册成功！").setIcon(R.drawable.ic_launcher)
						.setPositiveButton("确定", null).create().show();

				Intent intent1 = new Intent(RegisterActivity.this,
						LoginActivity.class);
				startActivity(intent1);
				break;
			case LOADING:
				progressDialog = ProgressDialog.show(RegisterActivity.this, "请稍等...", "读取中...", true);
				break;
			case UNLOADING:
				progressDialog.dismiss();
			// 其他异常
			default:
				new AlertDialog.Builder(RegisterActivity.this).setTitle("提示")
						.setMessage(msg.obj.toString())
						.setIcon(R.drawable.ic_launcher)
						.setPositiveButton("确定", null).create().show();
				break;
			}
		}

	};

	// 焦点事件
	@Override
	public void onFocusChange(View v, boolean isfocus) {
		if (!isfocus) {
			switch (v.getId()) {
			case R.id.editTextcode:
				if (code.getText().toString().contains("'")) {
					codeWarn.setText("邀请码不包含'");
				} else {
					codeWarn.setText("");
				}
				break;
			case R.id.EditTextUserNameRegister:
				if (username.getText().toString().contains("'")) {
					usernameWarn.setText("用户名不能包含'");
				} else {
					usernameWarn.setText("");
				}
				break;
			case R.id.editTextPasswordRegister:
				if (password.getText().length() > 16
						|| password.getText().length() < 6) {
					passwordWarn.setText("密码应在6-16位之间");
				} else {
					passwordWarn.setText("");
					ensurepassword.setText("");
				}
				break;
			case R.id.EditTextEnsurePassword:
				String p = password.getText().toString();
				String ensurep = ensurepassword.getText().toString();
				if (!p.equals(ensurep)) {
					ensurepasswordWarn.setText("密码输入不一致");
				} else {
					ensurepasswordWarn.setText("");
				}
				break;
			case R.id.editTextPhoneRegister:
				if (phone.getText().length() != 11) {
					phoneWarn.setText("请输入11位手机号");
				} else {
					phoneWarn.setText("");
				}
				break;
			case R.id.EditTextRealnameRegister:
				if (realname.getText().length() > 8
						|| realname.getText().length() < 2) {
					realnameWarn.setText("真实姓名应在2-8位之内");
				} else {
					realnameWarn.setText("");
				}
				break;
			case R.id.editText3IDcardRegister:
				if (idcard.getText().length() != 18) {
					idcardWarn.setText("请输入18位身份证号码");
				} else {
					idcardWarn.setText("");
				}
				break;
			default:
				break;
			}
		}

	}

	private boolean Check() {
		boolean flag = true;
		// 检查邀请码
		if (TextUtils.isEmpty(code.getText())) {
			codeWarn.setText("邀请码不能为空");
			flag = false;
		}
		if (!TextUtils.isEmpty(codeWarn.getText())) {
			flag = false;
		}
		// 检查用户名
		if (TextUtils.isEmpty(username.getText())) {
			usernameWarn.setText("用户名不能为空");
			flag = false;
		}
		if (!TextUtils.isEmpty(usernameWarn.getText())) {
			flag = false;
		}
		// 检查密码
		if (TextUtils.isEmpty(password.getText())) {
			passwordWarn.setText("密码不能为空");
			flag = false;
		}
		if (!TextUtils.isEmpty(passwordWarn.getText())) {
			flag = false;
		}
		// 检查验证密码
		if (TextUtils.isEmpty(ensurepassword.getText())) {
			ensurepasswordWarn.setText("验证密码不能为空");
			flag = false;
		}
		if (!TextUtils.isEmpty(ensurepasswordWarn.getText())) {
			flag = false;
		}
		// 检查电话号码
		if (TextUtils.isEmpty(phone.getText())) {
			phoneWarn.setText("电话号码不能为空");
			flag = false;
		}
		if (!TextUtils.isEmpty(phoneWarn.getText())) {
			flag = false;
		}
		// 检查真实姓名
		if (TextUtils.isEmpty(realname.getText())) {
			realnameWarn.setText("真实姓名不能为空");
			flag = false;
		}
		if (!TextUtils.isEmpty(realnameWarn.getText())) {
			flag = false;
		}
		// 检查身份证号
		if (TextUtils.isEmpty(idcard.getText())) {
			idcardWarn.setText("身份证号不能为空");
			flag = false;
		}
		if (!TextUtils.isEmpty(idcardWarn.getText())) {
			flag = false;
		}
		return flag;
	}
}
